package com.jiyinit.web.core.activiti.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jiyinit.core.framework.base.util.LogUtil;
import com.jiyinit.web.core.activiti.dto.EvectionDealRequest;
import com.jiyinit.web.core.activiti.dto.EvectionRequest;
import com.jiyinit.web.core.activiti.dto.LeaveDealRequest;
import com.jiyinit.web.core.activiti.entity.TabCoreEvectionDealEntity;
import com.jiyinit.web.core.activiti.entity.TabCoreEvectionEntity;
import com.jiyinit.web.core.activiti.entity.TabUserMemershipEntity;
import com.jiyinit.web.core.activiti.enums.ProcessFlowEnum;
import com.jiyinit.web.core.activiti.enums.evection.EveTaskGatewayEnum;
import com.jiyinit.web.core.activiti.enums.evection.EveUserTaskEnum;
import com.jiyinit.web.core.activiti.enums.evection.EvectionStatusEnum;
import com.jiyinit.web.core.activiti.service.EvectionDealServiceImpl;
import com.jiyinit.web.core.activiti.service.UserMemershipServiceImpl;
import com.jiyinit.web.core.activiti.vo.EveDealMindVo;
import com.jiyinit.web.core.activiti.vo.EveReviewVo;
import com.jiyinit.web.core.business.entity.TabCoreOrgEntity;
import com.jiyinit.web.core.business.entity.TabCoreUserEntity;
import com.jiyinit.web.core.business.service.OrgServiceImpl;
import com.jiyinit.web.core.business.service.UserServiceImpl;
import com.jiyinit.web.core.common.config.PropertyPlaceholderConfigurer;
import com.jiyinit.web.core.common.util.UserUtil;
import com.jiyinit.web.core.common.vo.LoginUserVo;
import com.jiyinit.web.core.common.vo.MobileUserVo;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang.BooleanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jiyinit.core.framework.base.entity.ResponseDto;
import com.jiyinit.core.framework.base.paging.PagingResult;
import com.jiyinit.core.framework.base.util.Check;
import com.jiyinit.core.framework.base.util.JsonEntityTransform;
import com.jiyinit.web.core.activiti.service.EvectionServiceImpl;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import static org.apache.shiro.web.filter.mgt.DefaultFilter.user;

@Controller
@RequestMapping(value = "mobile/evection")
public class EvectionController {
	
	private static Logger logger = LoggerFactory.getLogger(EvectionController.class);
	
	@Resource(name = "core.evectionServiceImpl")
	private EvectionServiceImpl evectionService;
	@Resource(name = "core.evectionDealServiceImpl")
	private EvectionDealServiceImpl evectionDealService;

	//节点处理人
	@Resource(name = "userMemershipServiceImpl")
	private UserMemershipServiceImpl userMemershipService;

	@Resource(name = "historyService")
	private HistoryService historyService;
	@Resource(name = "taskService")
	private TaskService taskservice;
	@Resource(name = "runtimeService")
	RuntimeService runtimeservice;

	@Resource(name = "core.orgServiceImpl")
	private OrgServiceImpl orgService;
	@Resource(name = "core.userServiceImpl")
	private UserServiceImpl userService;

	/**
	 * 发起出差申请：【保存包括更新】 逻辑接口
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(method = RequestMethod.POST,value = "saveEvection")//,consumes="application/json", produces="application/json"
	public ResponseEntity<ResponseDto> saveLeave(HttpServletRequest request,@RequestParam String request_json) {
		String logJson = request.getParameter("request_json");
		LogUtil.info(logger, "接口参数:{}", logJson);

		EvectionRequest billRequest = new EvectionRequest();
		try {
			if(!Check.isNullStrStrict(logJson)){
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				Map<?, ?> map = JsonEntityTransform.json2Map(logJson);
				String id = (String) map.get("id");
				String destination = (String)map.get("destination");
				String startTime = (String) map.get("startTime");
				String endTime = (String) map.get("endTime");
				String eveType = (String)map.get("eveType");
				String eveReason=(String)map.get("eveReason");
				String remarkInfo=(String)map.get("remarkInfo");
				String linkTel=(String)map.get("linkTel");
				DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
				Date start =dateFormat.parse(startTime);
				Date end =dateFormat.parse(endTime);

				if(Check.isNullStr(destination)){
					return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("目的地不能为空"), HttpStatus.OK);
				}else if (Check.isNullStr(endTime)){
					return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("出差结束时间不能为空"), HttpStatus.OK);
				}else if (Check.isNullStr(startTime)){
					return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("出差开始时间不能为空"), HttpStatus.OK);
				}else if (Check.isNullStr(eveType)){
					return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("出行方式不能为空"), HttpStatus.OK);
				}else if (Check.isNullObj(eveReason)){
					return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("出差原因不能为空"), HttpStatus.OK);
				}else if (Check.isNullObj(remarkInfo)){
					return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("备注信息不能为空"), HttpStatus.OK);
				}else if (Check.isNullObj(linkTel)){
					return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("联系电话不能为空"), HttpStatus.OK);
				}else{
					if(!Check.isNullStr(id)){
						billRequest.setId(Integer.valueOf(id));
					}else{
						billRequest.setId(null);
					}
					billRequest.setDestination(destination);
					billRequest.setEndTime(sdf.parse(endTime));
					billRequest.setStartTime(sdf.parse(startTime));
					billRequest.setEveType(eveType);
					billRequest.setEveReason(eveReason);
					billRequest.setRemarkInfo(remarkInfo);
					billRequest.setLinkTel(linkTel);
					if(billRequest.getEveReason().length()>100){
						return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("出差原因应小于100字"), HttpStatus.OK);
					}
					if(billRequest.getRemarkInfo().length()>100){
						return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("备注信息应小于100字"), HttpStatus.OK);
					} else if(start.getTime()>end.getTime()){
						return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("结束时间不能小于开始时间"), HttpStatus.OK);
					}
				}
			}else{
				return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("必传信息为空"), HttpStatus.OK);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		LoginUserVo loginUserVo = (LoginUserVo) JsonEntityTransform.json2Object(logJson, LoginUserVo.class);
		MobileUserVo vo= UserUtil.getMobileUser(loginUserVo.getToken());//根据token 用户id 获取用户所在部门信息（从session中取）

		TabCoreEvectionEntity record=new TabCoreEvectionEntity();
		BeanUtils.copyProperties(billRequest,record);
		record.setUserId(loginUserVo.getUserId());    //以session中的存储为准
		record.setOrgId(vo.getOrgId());     //以session中的存储为准
		record.setUserLeavel(vo.getLevel());    //以session中的存储为准
		record.setCreateTime(new Date());  //创建时间
		record.setIsDelete(0);  //未删除
		record.setIsAgree(0);//将状态设置为未提交
		record.setStatus(EvectionStatusEnum.WaitCommit.getCode());
		HashMap<String,Object> result =  new HashMap<String,Object>();
		int num = 0;
		if(Check.isNullObj(billRequest.getId())){
			synchronized (this){
				num = evectionService.add(record);
				int maxId = evectionService.getMaxIdByUserId(record.getUserId());
				//result.put("saveBean", record);
				result.put("key", maxId);
			}
		}else{
			num = evectionService.update(record);
			if(num > 0){
				//result.put("saveBean", record);
				result.put("key", record.getId());
			}else{
				return new ResponseEntity<>( ResponseDto.responseFail("更新失败"), HttpStatus.OK);
			}
		}

		return new ResponseEntity<>( ResponseDto.responseOK(result), HttpStatus.OK);
	}

	/**
	 * 【开始出差】 逻辑接口
	 * @param request  （只穿 id ，mobileUuid 即可）
	 * @return
	 */
	@ResponseBody
	@RequestMapping(method = RequestMethod.POST,value = "startEvection")//,consumes="application/json", produces="application/json"
	public ResponseEntity<ResponseDto> startLeave(HttpServletRequest request,@RequestParam String request_json) {
		String logJson = request.getParameter("request_json");
		LogUtil.info(logger, "接口参数:{}", logJson);
		EvectionRequest billRequest = new EvectionRequest();
		LoginUserVo loginUserVo = null;
		if(!Check.isNullStrStrict(logJson)){
			try {
				loginUserVo = (LoginUserVo) JsonEntityTransform.json2Object(logJson, LoginUserVo.class);
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				Map map = JsonEntityTransform.json2Map(logJson);
				String id = (String) map.get("id");
				billRequest.setId(Integer.valueOf(id));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			return new ResponseEntity<ResponseDto>(ResponseDto.responseFail(""), HttpStatus.OK);
		}

		//接收信息
		//判断客户端标识是否存在【必填项】
		if(billRequest.getId()==null){
			return new ResponseEntity<>(ResponseDto.responseFail("出差审批单主键不可以为空"), HttpStatus.OK);
		}
		//判断客户端标识是否存在【必填项】
        /*if(billRequest.getMobileuuid()==null||"".equals(billRequest.getMobileuuid())){
            return new ResponseEntity<>(ResponseDto.responseFail("客户端唯一标识不能为空"), HttpStatus.OK);
        }*/
		//查询订单信息 存在才能开始出差申请工作流
		TabCoreEvectionEntity record=new TabCoreEvectionEntity();
		record.setId(billRequest.getId());   //主键
		//record.setMobileuuid(billRequest.getMobileuuid()); //客户端唯一标识
		record.setIsDelete(0);  //未删除
		List<TabCoreEvectionEntity> livelist=evectionService.findBySelective(record);
		if(livelist.size()>0)
		{
			TabCoreEvectionEntity billBean=livelist.get(0);
			billBean.setStatus(EvectionStatusEnum.WaitReview.getCode());//提交时将状态设置为待审批
			//开启出差流程
			//1.启动一个实例（先判断实例是否启动）
			if(null!=billBean.getProcessId())
			{
				if(!("".equals(billBean.getProcessId().trim())))
					return new ResponseEntity<>(ResponseDto.responseFail("申请已经提交，禁止重复提交"), HttpStatus.OK);
			}

			MobileUserVo vo=UserUtil.getMobileUser(loginUserVo.getToken());
			ProcessInstance processInstance=evectionService.startWorkflow(billBean, ""+loginUserVo.getUserId());

			//2.完成当前任务。
			List<Task> list = taskservice.createTaskQuery().taskAssignee(""+vo.getUserId()).processInstanceId(processInstance.getId()).executionId(processInstance.getId()).orderByTaskCreateTime().asc().list();//使用创建时间的升序排列
			for(Task task:list){
				logger.info("--------"+task.getAssignee()+"任务:"+task.getName()+"-----------------");
				logger.info("任务ID:"+task.getId());
				logger.info("任务名称:"+task.getName());
				logger.info("任务的创建时间:"+task.getCreateTime());
				logger.info("任务的办理人:"+task.getAssignee());
				logger.info("流程实例ID："+task.getProcessInstanceId());
				logger.info("执行对象ID:"+task.getExecutionId());
				logger.info("流程定义ID:"+task.getProcessDefinitionId());
				if(task.getTaskDefinitionKey().trim().equals(EveUserTaskEnum.usertask1.getCode()))  //只有当时提出申请节点时 才自动拾取并提交
				{
					taskservice.complete(task.getId()); //完成
					//保存处理意见
					TabCoreEvectionDealEntity mindEntity=new TabCoreEvectionDealEntity();
					//mindEntity.setProcessId(processInstance.getId());
					mindEntity.setTaskName(task.getName());
					mindEntity.setTaskId(task.getId());
					mindEntity.setCreateDate(new Date());
					mindEntity.setDealUserid(vo.getUserId());
					mindEntity.setIsAgree("1");  //同意
					mindEntity.setDealInfo("提交出差申请");
					evectionDealService.add(mindEntity);
				}
			}
			return new ResponseEntity<>( ResponseDto.responseOK("流程启动成功"), HttpStatus.OK);
		}else{
			return new ResponseEntity<>(ResponseDto.responseFail("请先保存请假单"), HttpStatus.OK);
		}
	}

	/**
	 * 查询我的出差接口
	 * @param request
	 * @param request_json
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/queryMyEvectionS")
	public ResponseEntity<ResponseDto> queryMyEvectionS(HttpServletRequest request,@RequestParam String request_json){
		String logJson = request.getParameter("request_json");
		//LoginUserVo loginUserVo = (LoginUserVo) JsonEntityTransform.json2Object(logJson, LoginUserVo.class);
		Map map = JsonEntityTransform.json2Map(request_json);
		TabCoreEvectionEntity record=new TabCoreEvectionEntity();
		record.setUserId((Integer) map.get("userId"));
		/*Integer convertStatus = (Integer) map.get("convertStatus");
		if(!Check.isNullObj(convertStatus)){
			logger.info("查询类型: {}", convertStatus);
			record.setIsAgree(convertStatus);
		}*/
		List<TabCoreEvectionEntity> evectionList =evectionService.findBySelective(record);
		for(TabCoreEvectionEntity obj : evectionList){
			String processId = obj.getProcessId();
			if(Check.isNullStr(processId)){
				obj.setCurrentUserName(null);
			}else{
				String currentUserName = getCurrentUserNameByExecutionId(processId);
				obj.setCurrentUserName(currentUserName);
			}
		}
		return new ResponseEntity<>(ResponseDto.responseOK(evectionList), HttpStatus.OK);
	}
	/**
	 * 获取当前任务节点的办理人
	 * @param processId
	 * @return
	 */
	private String getCurrentUserNameByExecutionId(String processId){
		Task task = taskservice.createTaskQuery().processDefinitionKey(ProcessFlowEnum.Evection.getCode()).executionId(processId).singleResult();
		if(!Check.isNullObj(task)){
			String assignee = task.getAssignee();
			TabCoreUserEntity userEntity = getUserInfos(Integer.valueOf(assignee));
			return userEntity.getUserName();
		}
		return "";
	}


	/**
	 * 查询待办列表
	 * @param request
	 * @param request_json
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/queryWaitDoList")
	public ResponseEntity<ResponseDto> queryWaitDoList(HttpServletRequest request, @RequestParam String request_json) {
		String logJson = request.getParameter("request_json");
		LogUtil.info(logger, "接口参数:{}", logJson);
		EvectionRequest evectionRequest = (EvectionRequest) JsonEntityTransform.json2Object(logJson, EvectionRequest.class);
		LoginUserVo loginUserVo = (LoginUserVo) JsonEntityTransform.json2Object(logJson, LoginUserVo.class);

		ArrayList<EveReviewVo> reviewVos = new ArrayList<>();
		List<Task> tasks = taskservice.createTaskQuery().processDefinitionKey(ProcessFlowEnum.Evection.getCode()).taskCandidateOrAssigned(evectionRequest.getUserId() + "").listPage((evectionRequest.getPage() - 1) * evectionRequest.getLimit(), evectionRequest.getLimit());
		for (Task task : tasks) {
			String instanceid = task.getProcessInstanceId();
			/*ProcessInstance ins = runtimeservice.createProcessInstanceQuery().processInstanceId(instanceid).singleResult();
			String businesskey = ins.getBusinessKey();*/
			EvectionRequest newRequest = new EvectionRequest();
			newRequest.setLimit(10);
			newRequest.setProcessId(instanceid);
			PagingResult<TabCoreEvectionEntity> forPage = evectionService.findForPage(newRequest);
			List<TabCoreEvectionEntity> rows = forPage.getRows();
			TabCoreEvectionEntity evectionEntity = rows.get(0);
			EveReviewVo reviewVo = new EveReviewVo();
			BeanUtils.copyProperties(evectionEntity, reviewVo);
			reviewVo.setTaskId(task.getId());
			reviewVo.setProposerName(getUserInfos(evectionEntity.getUserId()).getUserName());
			reviewVo.setProposerOrgName(getOrgInfos(evectionEntity.getOrgId()).getOrgName());
			reviewVo.setDealUserName(getCurrentUserNameByExecutionId(task.getExecutionId()));
			reviewVo.setIsDispose("y");
			reviewVos.add(reviewVo);
		}
		List<EveReviewVo> dealTasks = evectionService.getDealTasksByUserId(loginUserVo.getUserId());
		for (EveReviewVo reviewVo : dealTasks) {
			reviewVo.setDealUserName(getCurrentUserNameByExecutionId(reviewVo.getProcessId()));
		}
		reviewVos.addAll(dealTasks);
		return new ResponseEntity<ResponseDto>(ResponseDto.responseOK(reviewVos), HttpStatus.OK);
	}

	/**
	 * 查询历史处理列表
	 * @param request
	 * @param request_json
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/queryHistoryList")
	public ResponseEntity<ResponseDto> queryHistoryList(HttpServletRequest request, @RequestParam String request_json) {
		logger.info("queryHistoryList 接口传入参数: {}", request_json);
		if(Check.isNullStr(request_json)){
			return new ResponseEntity<ResponseDto>(ResponseDto.responseFail(""), HttpStatus.OK);
		}
		Map<?,?> map = JsonEntityTransform.json2Map(request_json);
		String instanceid = (String) map.get("processId");
		List<HistoricTaskInstance> his = historyService.createHistoricTaskInstanceQuery()
				.processInstanceId(instanceid)
				.orderByDueDateNullsLast().asc().list();

		ArrayList<EveDealMindVo> dealMindVos = new ArrayList<>();
		EvectionDealRequest dealRequest = new EvectionDealRequest();

		for (HistoricTaskInstance task : his) {
			EveDealMindVo dealMindVo = new EveDealMindVo();
			dealRequest.setTaskId(task.getId());
			PagingResult<TabCoreEvectionDealEntity> pagingResult = evectionDealService.findForPage(dealRequest);
			List<TabCoreEvectionDealEntity> rows = pagingResult.getRows();
			if(!Check.isNullCollection(rows)){
				TabCoreEvectionDealEntity dealEntity = rows.get(0);
				dealMindVo.convertFor(dealEntity);
			}
			dealMindVo.setTaskName(task.getName());
			dealMindVo.setTaskDefinitionKey(task.getTaskDefinitionKey());
			if(!Check.isNullStr(task.getAssignee())) {
				TabCoreUserEntity user = userService.getUserInfoByUserId(Integer.parseInt(task.getAssignee()));
				dealMindVo.setDealUserName(user.getUserName());  //用户名字
			}
			dealMindVos.add(dealMindVo);
		}
		return new ResponseEntity<ResponseDto>(ResponseDto.responseOK(dealMindVos), HttpStatus.OK);
	}






	/**
	 * 我的待办：【处理出差】 逻辑接口
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(method = RequestMethod.POST,value = "/disposeEvection")
	public ResponseEntity<ResponseDto> evection(HttpServletRequest request,@RequestParam String request_json) {
		String logJson = request.getParameter("request_json");
		LogUtil.info(logger, "接口参数:{}", logJson);
		if(!Check.isNullStr(logJson)){
			LoginUserVo loginUserVo = (LoginUserVo) JsonEntityTransform.json2Object(logJson, LoginUserVo.class);
			EvectionDealRequest evectionDealRequest = JsonEntityTransform.json2Object(logJson, EvectionDealRequest.class);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			Map map = JsonEntityTransform.json2Map(logJson);
			boolean isAgree = getIsAgree(evectionDealRequest.getIsAgree());

			if(isAgree){
				evectionDealRequest.setIsAgree("1");//1代表同意
			}else{
				evectionDealRequest.setIsAgree("0");//0为不同意
			}

			//根据token 用户id 获取用户所在部门信息（从session中取）
			MobileUserVo vo= UserUtil.getMobileUser(loginUserVo.getToken());

			if(Check.isNullStr(evectionDealRequest.getProcessId())){
				return new ResponseEntity<>(ResponseDto.responseFail("无法获取任务id"), HttpStatus.OK);
			}

			if(Check.isNullStr(evectionDealRequest.getTaskId())){
				return new ResponseEntity<>(ResponseDto.responseFail("无法获取任务id"), HttpStatus.OK);
			}

			if(Check.isNullStr(evectionDealRequest.getDealInfo())){
				evectionDealRequest.setDealInfo("");
			}

			if(Check.isNullStr(evectionDealRequest.getIsAgree()))
			{
				return new ResponseEntity<>(ResponseDto.responseFail("处理类型为必选项"), HttpStatus.OK);
			}


			//判断当前用户是否是主要负责人
			Task task=taskservice.createTaskQuery().taskId(evectionDealRequest.getTaskId()).taskCandidateOrAssigned(loginUserVo.getUserId()+"").singleResult();
			if(null==task)
			{
				return new ResponseEntity<>(ResponseDto.responseFail("请求非法，稍后再试"), HttpStatus.OK);
			}

			//+++++++++++++++++++++++++++++++++处理原则：存在组关系时 必须是主管领导才可以处理 否则 没有权限；若不存在组关系 且是他自己时 便可以处理自己的单子+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
			TabUserMemershipEntity shipEntity=new TabUserMemershipEntity();
			//        shipEntity.setOrgId(vo.getOrgId());  //部门  先不判断
			shipEntity.setGroupKey(task.getTaskDefinitionKey());
			shipEntity.setProcinstKey(ProcessFlowEnum.Evection.getCode());
			shipEntity.setIsDelete("0");  //未删除
			// shipEntity.setIsMain("1");  //主要负责人
			List<TabUserMemershipEntity> shipList= userMemershipService.findBySelective(shipEntity);
			if(shipList.size()>0)  //存在并且是主管领导
			{
				TabUserMemershipEntity ship=shipList.get(0);
				if(!ship.getIsMain().equals("1"))
					return new ResponseEntity<>(ResponseDto.responseFail("只有主管领导才能处理"), HttpStatus.OK);
			}

			//开始节点处理
			String agreeStr="false";
			if(evectionDealRequest.getIsAgree().equals("1")){agreeStr="true";}   //同意请假 其他回退
			Map mapVar=new HashMap();  //同意意见节点变量
			mapVar.put(EveTaskGatewayEnum.getGatewayCode(task.getTaskDefinitionKey()),agreeStr);


			taskservice.claim(task.getId(),vo.getUserId()+"");  //先拾取

			//如果是最后一个节点  特殊处理（归档时）更新请假记录
			ProcessInstance process=null;
			if(task.getTaskDefinitionKey().equals(EveUserTaskEnum.usertask4.getCode()))
			{
				process=runtimeservice.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
				taskservice.complete(task.getId());
			}else {
				process=runtimeservice.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
				taskservice.complete(task.getId(), mapVar);
			}
			//保存处理意见
			TabCoreEvectionDealEntity record=new TabCoreEvectionDealEntity();
			BeanUtils.copyProperties(evectionDealRequest,record);
			record.setTaskName(task.getName());
			record.setTaskId(task.getId());
			record.setCreateDate(new Date());
			record.setDealUserid(vo.getUserId());
			record.setIsAgree(evectionDealRequest.getIsAgree());
			record.setProcessId(task.getExecutionId());
			evectionDealService.add(record);

			if(agreeStr.equals("false")){
				TabCoreEvectionEntity evectionEntity=new TabCoreEvectionEntity();
				evectionEntity.setId(new Integer(process.getBusinessKey()));
				evectionEntity.setModifyTime(new Date());
				evectionEntity.setStatus(EvectionStatusEnum.Refuse.getCode());   //将状态设置为拒绝状态
				evectionService.update(evectionEntity);
			}
			//如果是最后一个节点  特殊处理（归档时）更新请假记录
			if(task.getTaskDefinitionKey().equals(EveUserTaskEnum.usertask4.getCode()))
			{
				TabCoreEvectionEntity evectionEntity=new TabCoreEvectionEntity();
				evectionEntity.setId(new Integer(process.getBusinessKey()));
				evectionEntity.setModifyTime(new Date());
				evectionEntity.setStatus(EvectionStatusEnum.Recorded.getCode());   //将状态设置为已备案状态
				evectionService.update(evectionEntity);
			}
			return new ResponseEntity<>( ResponseDto.responseOK("任务处理完成"), HttpStatus.OK);
		}
		return new ResponseEntity<>( ResponseDto.responseFail(""), HttpStatus.OK);
	}
	public boolean getIsAgree(String str){
		if(Check.isNullStrStrict(str))throw new NullPointerException("isAgree is null");
		if("true".equals(str) || "false".equals(str)){
			return BooleanUtils.toBoolean(str);
		}else{
			return BooleanUtils.toBoolean(Integer.valueOf(str));
		}
	}

	/**
	 * 查询下个环节的审批人
	 * @param request
	 * @param request_json
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/queryReviewUsers")
	public ResponseEntity<ResponseDto> queryReviewUsers(HttpServletRequest request,@RequestParam String request_json) {
		JSONObject jsonObject = JSON.parseObject(request_json);
		String id = (String)jsonObject.get("id");
		LoginUserVo loginUserVo = (LoginUserVo) JsonEntityTransform.json2Object(request_json, LoginUserVo.class);
		Integer userId = loginUserVo.getUserId();

		List<TabCoreUserEntity> reviewUserList = new ArrayList<>();

		TabCoreEvectionEntity billEntity=new TabCoreEvectionEntity();
		billEntity.setId(Integer.valueOf(id));
		billEntity.setUserId(userId);
		List<TabCoreEvectionEntity> billList = evectionService.findBySelective(billEntity);
		if(!Check.isNullCollection(billList)){
			billEntity = billList.get(0);
			String taskKey = "";
			TabCoreUserEntity taskReviewUser = null;
			switch (billEntity.getUserLeavel()){
				case 1:
					taskKey = EveUserTaskEnum.usertask2.getCode();
					taskReviewUser = getTaskReviewUser(billEntity, false, taskKey);
					reviewUserList.add(taskReviewUser);

					taskKey = EveUserTaskEnum.usertask3.getCode();
					taskReviewUser = getTaskReviewUser(billEntity, true, taskKey);
					reviewUserList.add(taskReviewUser);

					taskKey = EveUserTaskEnum.usertask4.getCode();
					taskReviewUser = getTaskReviewUser(billEntity, true, taskKey);
					reviewUserList.add(taskReviewUser);
					break;
				case 2:
					taskKey = EveUserTaskEnum.usertask3.getCode();
					taskReviewUser = getTaskReviewUser(billEntity, true, taskKey);
					reviewUserList.add(taskReviewUser);

					taskKey = EveUserTaskEnum.usertask4.getCode();
					taskReviewUser = getTaskReviewUser(billEntity, true, taskKey);
					reviewUserList.add(taskReviewUser);
					break;
				default:
					break;
			}
		}
		return new ResponseEntity<>(ResponseDto.responseOK(reviewUserList), HttpStatus.OK);
	}

	/**
	 * 根据任务key查询节点处理人
	 * @param billEntity
	 * @return
	 */
	private TabCoreUserEntity getTaskReviewUser(TabCoreEvectionEntity billEntity, boolean isTask12, String taskKey){
		TabUserMemershipEntity shipEntity = new TabUserMemershipEntity();
		if(isTask12){
			shipEntity.setOrgId(null);
		}else{
			shipEntity.setOrgId(billEntity.getOrgId());
		}
		shipEntity.setGroupKey(taskKey);
		shipEntity.setProcinstKey(ProcessFlowEnum.Evection.getCode());
		shipEntity.setIsDelete("0");  //未删除
		List<TabUserMemershipEntity> shipList= userMemershipService.findBySelective(shipEntity);
		Integer mainUserId = 0;
		for (TabUserMemershipEntity shipBean:shipList) {
			if(shipBean.getIsMain().equals("1")) {
				mainUserId = shipBean.getUserId();
			}
		}
		return getUserInfos(mainUserId);
	}




















	/**
	 * 获取用户信息
	 * @param userId
	 * @return
	 */
	public TabCoreUserEntity getUserInfos(Integer userId){
		return userService.getUserInfoByUserId(userId);
	}

	/**
	 * 获取部门信息
	 * @param orgId
	 * @return
	 */
	public TabCoreOrgEntity getOrgInfos(Integer orgId) {
		return orgService.selectById(orgId);
	}


}
